package com.cleaningcloud.cld.controller.mini;

import com.alibaba.fastjson2.JSONObject;
import com.cleaningcloud.cld.api.domain.CldProjectAccount;
import com.cleaningcloud.cld.api.domain.CldStaff;
import com.cleaningcloud.cld.api.model.LoginStaff;
import com.cleaningcloud.cld.domain.dto.CldProjectPostDto;
import com.cleaningcloud.cld.domain.dto.CldTrainPlanDto;
import com.cleaningcloud.cld.domain.mini.PostInfo;
import com.cleaningcloud.cld.domain.mini.UserInfo;
import com.cleaningcloud.cld.domain.vo.CldProjectPostSetVo;
import com.cleaningcloud.cld.domain.vo.CldTrainPlanVo;
import com.cleaningcloud.cld.service.ICldProjectAccountService;
import com.cleaningcloud.cld.service.ICldProjectPostService;
import com.cleaningcloud.cld.service.ICldStaffService;
import com.cleaningcloud.cld.service.ICldTrainPlanService;
import com.cleaningcloud.cld.service.mini.IMiniPersonnelService;
import com.cleaningcloud.common.core.constant.SecurityConstants;
import com.cleaningcloud.common.core.domain.R;
import com.cleaningcloud.common.core.utils.StringUtils;
import com.cleaningcloud.common.core.web.controller.BaseController;
import com.cleaningcloud.common.core.web.domain.AjaxResult;
import com.cleaningcloud.common.security.annotation.InnerAuth;
import com.cleaningcloud.common.security.utils.DictUtils;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import com.cleaningcloud.erp.api.RemoteWareService;
import com.cleaningcloud.erp.api.domain.ErpWareHouse;
import com.cleaningcloud.system.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 员工基础信息 - 小程序接口
 */
@RestController
@RequestMapping("/mini/basicInfo")
public class MiniBasicInformationController extends BaseController {


    @Autowired
    private ICldStaffService cldStaffService;

    @Autowired
    private ICldProjectPostService cldProjectPostService;

    @Autowired
    private ICldProjectAccountService projectAccountService;

    @Autowired
    private ICldTrainPlanService cldTrainPlanService;

    @Autowired
    private IMiniPersonnelService miniPersonnelService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RemoteWareService remoteWareService;

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/staff/info/{staffPhone}")
    public R<LoginStaff> info(@PathVariable("staffPhone") String staffPhone) {
        CldStaff cldStaff = cldStaffService.selectStaffByStaffPhone(staffPhone);
        CldProjectAccount cldProjectAccount = projectAccountService.selectAccountByAccountPhone(staffPhone);
        Map<String, Object> sysMap = remoteUserService.getUserInfoByPhone(staffPhone, SecurityConstants.INNER);
        if (StringUtils.isNull(cldStaff) && cldProjectAccount == null && sysMap == null) {
            return R.fail("用户名或密码错误");
        }
        LoginStaff loginStaff = new LoginStaff();
        Long userId = null;
        String userName = null;

        if (cldStaff != null) {
            loginStaff.setLoginType(1);
            userId = cldStaff.getStaffId();
            userName = cldStaff.getStaffName();
            loginStaff.setCldStaff(cldStaff);
        } else if (cldProjectAccount != null) {
            userId = cldProjectAccount.getProjectAccountId();
            userName = cldProjectAccount.getUserName();
            loginStaff.setLoginType(2);
            loginStaff.setProjectAccount(cldProjectAccount);
        } else {
            if (sysMap.get("userId") != null) {
                userId = Long.valueOf(sysMap.get("userId").toString());
            }
            if (sysMap.get("username") != null) {
                userName = sysMap.get("username").toString();
            }
            if (sysMap.get("phone") != null) {
                loginStaff.setPhone(sysMap.get("phone").toString());
            }
            if (sysMap.get("password") != null) {
                loginStaff.setPassword(sysMap.get("password").toString());
            }
            loginStaff.setLoginType(3);
            if (sysMap.get("postId") != null) {
                loginStaff.setPostId(sysMap.get("postId").toString());
            }
            // 查询系统用户是否为审核员
            CldTrainPlanDto trainPlanDto = new CldTrainPlanDto();
            trainPlanDto.setTrainAuditorType("1");
            trainPlanDto.setTrainAuditorId(userId);
            List<CldTrainPlanVo> trainPlanVos = cldTrainPlanService.selectCldTrainPlanList(trainPlanDto);
            if (!trainPlanVos.isEmpty()) {
                loginStaff.setPostId("-1");
            }
        }
        loginStaff.setUserId(userId);
        loginStaff.setUserName(userName);
        return R.ok(loginStaff);
    }


    /**
     * 根据手机号查询客户信息
     */
    @InnerAuth
    @GetMapping("/projectAccount/info/{accountPhone}")
    public R<LoginStaff> projectAccount(@PathVariable("accountPhone") String accountPhone) {
        CldProjectAccount cldProjectAccount = projectAccountService.selectAccountByAccountPhone(accountPhone);
        if (StringUtils.isNull(cldProjectAccount)) {
            return R.fail("用户名或密码错误");
        }
        LoginStaff loginStaff = new LoginStaff();
        loginStaff.setUserId(cldProjectAccount.getProjectAccountId());
        loginStaff.setUserName(cldProjectAccount.getUserName());
        loginStaff.setLoginType(2);
        loginStaff.setProjectAccount(cldProjectAccount);
        return R.ok(loginStaff);
    }

    /**
     * 注册员工信息
     */
    @InnerAuth
    @PostMapping("/staff/register")
    public R<Boolean> register(@RequestBody CldStaff cldStaff) {
        String staffPhone = cldStaff.getStaffPhone();
        if (!cldStaffService.checkUserPhoneUnique(cldStaff)) {
            return R.fail("保存员工'" + staffPhone + "'失败，该手机号已存在");
        }
        return R.ok(cldStaffService.registerStaff(cldStaff));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        Map<String, String> projectPostMap = DictUtils.getDictDataMap("cld_project_post");
        Map<String, String> projectPostDuitsMap = DictUtils.getDictDataMap("cld_project_duits");
        Map<String, String> projectPostGroupsMap = DictUtils.getDictDataMap("cld_project_groups");
        UserInfo userInfo = new UserInfo();
        // 获取登录用户类型
        LoginStaff loginStaff = SecurityUtils.getLoginStaff();
        if (loginStaff.getLoginType() == 1) {
            userInfo = miniPersonnelService.selectStaffAttributesByStaffId(loginStaff.getUserId());
            CldProjectPostDto cldProjectPostDto = new CldProjectPostDto();
            cldProjectPostDto.setStaffId(loginStaff.getUserId());
            List<CldProjectPostSetVo> postList = cldProjectPostService.selectCldProjectPostList(cldProjectPostDto);
            List<PostInfo> postInfoList = new ArrayList<>();
            for (CldProjectPostSetVo cldProjectPostSetVo : postList) {
                PostInfo postInfo = new PostInfo();
                postInfo.setProjectPostId(cldProjectPostSetVo.getProjectPostId());
                postInfo.setProjectId(cldProjectPostSetVo.getProjectId());
                postInfo.setPostId(cldProjectPostSetVo.getProjectPostName());
                if (cldProjectPostSetVo.getProjectPostName() != null) {
                    postInfo.setPostName(projectPostMap.get(cldProjectPostSetVo.getProjectPostName().toString()));
                }
                postInfo.setDuitsId(cldProjectPostSetVo.getProjectDuitsName());
                if (cldProjectPostSetVo.getProjectDuitsName() != null) {
                    postInfo.setDuitsName(projectPostDuitsMap.get(cldProjectPostSetVo.getProjectDuitsName().toString()));
                }
                postInfo.setGroupId(cldProjectPostSetVo.getGroupName());
                if (cldProjectPostSetVo.getGroupName() != null) {
                    postInfo.setGroupName(projectPostGroupsMap.get(cldProjectPostSetVo.getGroupName().toString()));
                }
                postInfo.setCldClasses(cldProjectPostSetVo.getCldClasses());
                postInfo.setMain(cldProjectPostSetVo.getIsMasterDuits() != null && cldProjectPostSetVo.getIsMasterDuits() != 0L);
                ErpWareHouse materialIn = new ErpWareHouse();
                if (cldProjectPostSetVo.getProjectPostName() == 1) {
                    materialIn = remoteWareService.getWareHouseByProjectId(cldProjectPostSetVo.getProjectId(), SecurityConstants.INNER);
                } else {
                    materialIn = remoteWareService.getWareHouseByPostId(cldProjectPostSetVo.getProjectPostId(), SecurityConstants.INNER);
                }
                if (materialIn == null) {
                    throw new RuntimeException("个人仓查询失败");
                }
                postInfo.setPostWareId(materialIn.getWareId());
                postInfoList.add(postInfo);
            }
            userInfo.setStaff(cldStaffService.selectCldStaffByStaffId(loginStaff.getUserId()));
            userInfo.setPostList(postInfoList);
            // 判断是否为员工 待入职和已入职状态区分
            if (userInfo.getStaff().getStaffStatus() == 0 || userInfo.getStaff().getStaffStatus() == 1) {
                userInfo.setEmployee(true);
            }
            userInfo.setAvatar(userInfo.getStaff().getAvatar());
            userInfo.setUserId(userInfo.getStaff().getStaffId());
            userInfo.setUserName(userInfo.getStaff().getStaffName());
        }
        if (loginStaff.getLoginType() == 2) {
            userInfo.setProjectAccount(projectAccountService.selectCldProjectAccountByProjectAccountId(loginStaff.getUserId()));
            userInfo.setAccount(true);
            userInfo.setUserId(userInfo.getProjectAccount().getProjectAccountId());
            userInfo.setUserName(userInfo.getProjectAccount().getUserName());
        }
        if (loginStaff.getLoginType() == 3) {
            Map<String, Object> sysMap = remoteUserService.getUserInfoByUserId(loginStaff.getUserId(), SecurityConstants.INNER);
            userInfo.setUser(sysMap.get("user"));
            if (sysMap.get("postId") != null) {
                String postId = sysMap.get("postId").toString();
                if (postId.equals("2")) {
                    userInfo.setOperationsManage(true);
                }
                if (postId.equals("10")) {
                    userInfo.setRepair(true);
                }
            }
            // 查询系统用户是否为审核员
            CldTrainPlanDto trainPlanDto = new CldTrainPlanDto();
            trainPlanDto.setTrainAuditorType("1");
            trainPlanDto.setTrainAuditorId(loginStaff.getUserId());
            List<CldTrainPlanVo> trainPlanVos = cldTrainPlanService.selectCldTrainPlanList(trainPlanDto);
            if (!trainPlanVos.isEmpty()) {
                userInfo.setTrainPlanAudit(true);
            }
            // 转换为json
            JSONObject jsonObject = JSONObject.from(userInfo.getUser());
            userInfo.setAvatar(jsonObject.getString("avatar"));
            userInfo.setUserId(jsonObject.getLong("userId"));
            userInfo.setUserName(jsonObject.getString("nickName"));
        }
        return success(userInfo);
    }

}
